const axios = require('axios')
const formatDate = require('../../lib/formatDate')
const crypto = require('crypto')
const logger = require('log4js').getLogger()

const access_token = '32eae3e9-c04c-4416-b5cf-e55cb6023892'
const app_key = '6604000BF0481A8D13C0F62E5D37FB45'
const app_secret = '2858d6feb1bc45da8c37d4fea5416a80'
const format = 'json'
const v = '2.0'
const unionId = '1000369453'

const jingdong = {
	Service: {
		promotion: {
			batch: {
				getcode(link) {
					if (link.indexOf('jd') == -1)
						return Promise.reject()
					if (link.indexOf('?') != -1)
						link = link.substring(0, link.indexOf('?'))
					var obj = {
						'360buy_param_json': JSON.stringify({
							id: '',
							url: link,
							unionId: '1000369453',
							subUnionId: '',
							channel: '',
							webId: '1015309151',
							positionId: '',
							ext1: '',
							protocol: '',
							pid: ''
						}),
						access_token: '32eae3e9-c04c-4416-b5cf-e55cb6023892',
						app_key: '6604000BF0481A8D13C0F62E5D37FB45',
						method: 'jingdong.service.promotion.batch.getcode',
						timestamp: formatDate(new Date()),
						v: '2.0'
					}
					var str = ''
					for (var key in obj)
						str += key + obj[key]
					str = '2858d6feb1bc45da8c37d4fea5416a80' + str + '2858d6feb1bc45da8c37d4fea5416a80'
					var sign = crypto.createHash("md5").update(str).digest("hex").toUpperCase()
					var url = 'https://api.jd.com/routerjson?sign=' + sign
					for (var key in obj)
						url += '&' + key + '=' + obj[key]
					logger.info('[' + __filename + ':' + __line + ']', url)
					return new Promise((resolve, reject) => {
						require('../util/getHtml')({
							url
						}).then(result => {
							logger.debug('[' + __filename + ':' + __line + ']', result)
							resolve()
						}, result => {
							if (result)
								logger.error('[' + __filename + ':' + __line + ']', result)
							reject()
						})
					})
				}
			}
		}
	},
	UnionService: {
		queryOrderList(time, pageIndex) {
			pageIndex = pageIndex || 1
			var obj = {
				'360buy_param_json': JSON.stringify({
					unionId: unionId,
					time: time,
					pageIndex: pageIndex,
					pageSize: 500
				}),
				access_token: access_token,
				app_key: app_key,
				format: format,
				method: 'jingdong.UnionService.queryOrderList',
				timestamp: formatDate(new Date()),
				v: v
			}
			var str = ''
			for (var key in obj)
				str += key + obj[key]
			str = app_secret + str + app_secret
			var sign = crypto.createHash("md5").update(str).digest("hex").toUpperCase()
			var url = 'https://api.jd.com/routerjson?sign=' + sign
			for (var key in obj)
				url += '&' + key + '=' + obj[key]
			return new Promise((resolve, reject) => {
				axios.get(url).then(response => {
					var result = response.data
					if (result.jingdong_UnionService_queryOrderList_responce &&
						result.jingdong_UnionService_queryOrderList_responce.code == '0' &&
						result.jingdong_UnionService_queryOrderList_responce.result) {
						result = JSON.parse(result.jingdong_UnionService_queryOrderList_responce.result)
						if (result.success) {
							result.data = result.data || []
							if (result.hasMore) {
								jingdong.UnionService.queryOrderList(time, pageIndex + 1).then(_result => {
									result.data.push.apply(result.data, _result)
									resolve(result.data)
								}, _result => {
									if (_result)
										logger.error('[' + __filename + ':' + __line + ']', _result)
									reject()
								})
								return
							}
							resolve(result.data)
							return
						}
					}
					logger.error('[' + __filename + ':' + __line + ']', JSON.stringify(response.data))
					reject()
				}, result => {
					if (result)
						logger.error('[' + __filename + ':' + __line + ']', result)
					reject()
				})
			})
		}
	}
}

module.exports = jingdong